#include <stdio.h>  // for printf
#include <string.h> // for memory operation
#include <stdlib.h>
#include <unistd.h>  // for sleep
#include "ohos_init.h"
#include "cmsis_os2.h"

#include "lwip/sockets.h"

#include "lwip/netifapi.h"
#include "wifi_sta_connect.h"

#define AP_SSID "MY_SW"
#define AP_PWD  "12345678"

void sta_test_entry(void *arg)
{
    printf("start sta test\n");
    WifiConnect(AP_SSID,AP_PWD);

    while(1)
    {
        sleep(1);
    }

     /****************以下为UDP服务器代码,默认IP:192.168.5.1***************/
	//在sock_fd 进行监听
    int sock_fd;
    //服务端地址信息
	struct sockaddr_in server_sock;

    //创建socket
	if ((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
	{
		perror("socket is error.\r\n");
		return -1;
	}

    printf("=== > sock_fd=%d\n",sock_fd);
    const int opt=-1;
    //设置套接字类型

	// bzero(&server_sock, sizeof(server_sock));
	server_sock.sin_family = AF_INET;
	server_sock.sin_addr.s_addr = htonl(INADDR_ANY);
	server_sock.sin_port = htons(7788);

	//调用bind函数绑定socket和地址
	if (bind(sock_fd, (struct sockaddr *)&server_sock, sizeof(struct sockaddr)) == -1)
	{
		perror("bind is error.\r\n");
		return -1;
	}

    int ret;
    char recvBuf[128] = {0};
    char sendBuff[128] ={ 0};
    //客户端地址信息
    struct sockaddr_in send_addr;
    int size_send_addr= sizeof(struct sockaddr_in);
    send_addr.sin_family = AF_INET;
    send_addr.sin_addr.s_addr = inet_addr("192.168.43.106");
    send_addr.sin_port = htons(3861);
    int count = 0;
    while (1)
    {
        memset(recvBuf, 0, sizeof(recvBuf));
        
        
        sprintf_s(sendBuff,sizeof(sendBuff),"Hello I'm sw ++%d\n",count);
        printf("sendbuff:%s\n",sendBuff);

        //发送数据
        ret = sendto(sock_fd, sendBuff, strlen(sendBuff), 0, 
        (struct sockaddr *)&send_addr, (socklen_t)size_send_addr);
        if (ret < 0)
        {
            printf("UDP server send failed!\r\n");
            // return -1;
        }

        ret = recvfrom(sock_fd, recvBuf, sizeof(recvBuf), 0, 
        (struct sockaddr *)&send_addr,(socklen_t*)&size_send_addr);
        if (ret < 0)
        {
            printf("UDP recv  failed! ret = %d\r\n",ret);
            // return -1;
        }
        printf("recv:%s,ipaddr:%s\n",recvBuf,inet_ntoa(send_addr.sin_addr),count++);
        
        // sleep(3);
    }
    /*********************END********************/
}

void sta_test_main()
{
    osThreadAttr_t attr;

    attr.name = "sta_test";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 10240;
    attr.priority = 25;

    if (osThreadNew((osThreadFunc_t)sta_test_entry, NULL, &attr) == NULL)
    {
        printf("Falied to create wifi sta!\r\n");
    }
}

APP_FEATURE_INIT(sta_test_main);